//
// Created by kyle on 25-7-16.
//

#ifndef MAIN_H
#define MAIN_H

#include <ft2build.h>
#include FT_FREETYPE_H
#include <vector>
#include <string>
#include <algorithm>
#include <cmath>
static std::unordered_map<std::string, std::string> parse_args(int argc, char *argv[]);

struct Size {
    int width;
    int height;
};

struct TextMetrics {
    int max_font_size;
    int line_height;
    int lines;
};

TextMetrics calculate_max_font_size(
    const std::string& text,
    const std::string& font_path,
    int screen_width,
    int screen_height,
    int initial_font_size = 100,  // 初始尝试的字体大小
    int min_font_size = 1,        // 最小字体大小
    int max_font_size = 1000      // 最大字体大小
) {
    FT_Library library;
    if (FT_Init_FreeType(&library)) {
        throw std::runtime_error("Could not initialize FreeType library");
    }

    FT_Face face;
    if (FT_New_Face(library, font_path.c_str(), 0, &face)) {
        FT_Done_FreeType(library);
        throw std::runtime_error("Failed to load font");
    }

    TextMetrics result = {0, 0, 0};
    int low = min_font_size;
    int high = max_font_size;
    int best_size = 0;

    // 使用二分查找找到最大合适的字体大小
    while (low <= high) {
        int current_size = (low + high) / 2;

        if (FT_Set_Pixel_Sizes(face, 0, current_size)) {
            high = current_size - 1;
            continue;
        }

        // 计算行高
        int line_height = face->size->metrics.height >> 6;

        // 分割文本为单词
        std::vector<std::string> words;
        size_t start = 0;
        size_t end = text.find(' ');
        while (end != std::string::npos) {
            words.push_back(text.substr(start, end - start));
            start = end + 1;
            end = text.find(' ', start);
        }
        words.push_back(text.substr(start));

        // 计算换行后的总高度和最大宽度
        int current_line_width = 0;
        int total_height = line_height;
        int max_line_width = 0;
        bool fits = true;

        for (const auto& word : words) {
            // 计算单词宽度
            int word_width = 0;
            for (char c : word) {
                if (FT_Load_Char(face, c, FT_LOAD_RENDER)) {
                    continue;
                }
                word_width += face->glyph->advance.x >> 6;
            }

            // 检查单词是否适合当前行
            if (current_line_width == 0) {
                // 新行
                if (word_width > screen_width) {
                    fits = false;
                    break;
                }
                current_line_width = word_width;
            } else {
                // 检查是否需要在当前行添加空格
                int space_width = 0;
                if (FT_Load_Char(face, ' ', FT_LOAD_RENDER) == 0) {
                    space_width = face->glyph->advance.x >> 6;
                }

                if (current_line_width + space_width + word_width <= screen_width) {
                    current_line_width += space_width + word_width;
                } else {
                    // 换行
                    max_line_width = std::max(max_line_width, current_line_width);
                    current_line_width = word_width;
                    total_height += line_height;

                    if (total_height > screen_height || word_width > screen_width) {
                        fits = false;
                        break;
                    }
                }
            }
        }

        max_line_width = std::max(max_line_width, current_line_width);

        if (fits && max_line_width <= screen_width && total_height <= screen_height) {
            // 当前大小合适，尝试更大的
            best_size = current_size;
            result.max_font_size = current_size;
            result.line_height = line_height;
            result.lines = (total_height + line_height - 1) / line_height; // 计算行数
            low = current_size + 1;
        } else {
            // 当前大小太大，尝试更小的
            high = current_size - 1;
        }
    }

    FT_Done_Face(face);
    FT_Done_FreeType(library);

    if (best_size == 0) {
        throw std::runtime_error("No suitable font size found that fits the given dimensions");
    }

    return result;
}
#endif //MAIN_H
